package org.mcflier.appuntamento.io.driver.rss;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.util.logging.Logger;

import org.mcflier.appuntamento.core.Factory;
import org.mcflier.appuntamento.core.exception.ModulesException;
import org.mcflier.appuntamento.core.logger.LoggerManager;

public class RssTools {
	
	public static File getRSSContentFile(String link) throws IOException{
		URL url;
		Logger logger = null;
		try {
			logger = ((LoggerManager)Factory.getInstance().getModuleInstance(Factory.MODULE_LOGGER)).getLogger(RssTools.class.getName());
		} catch (ModulesException e) {}

		if(logger!=null) logger.info("Reading content from rss source: "+link);
		url = new URL(link);
		HttpURLConnection con = (HttpURLConnection)url.openConnection();
		//con.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; MacOS X)");
		con.addRequestProperty("User-Agent", "Appuntamento; "+System.getProperty("os.name")+" "+System.getProperty("os.version")+")");

		BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
		File tempFile = File.createTempFile("RSS_List", ".rss");
		PrintWriter writer = new PrintWriter(tempFile);
		
		String inputLine;
		while ((inputLine = reader.readLine()) != null){
			writer.println(inputLine);
		}
		reader.close();
		writer.close();
		
		return tempFile;
	}
	
	public static Timestamp convertToTimestamp(String s){
		//input example: Sat, 10 Aug 2013 10:46:05 GMT
		Logger logger = null;
		try {
			logger = ((LoggerManager)Factory.getInstance().getModuleInstance(Factory.MODULE_LOGGER)).getLogger(RssTools.class.getName());
		} catch (ModulesException e1) {}
		if(s==null) return null;
		try {
			s = s.substring(s.indexOf(" ")+1, s.lastIndexOf(" "));
			String[] tokens = s.split(" ");
			tokens[1] = tokens[1].toLowerCase();
			
			switch(tokens[1].charAt(0)){
				case 'j':
					switch(tokens[1].charAt(1)){
						case 'a':
							tokens[1] = "01";
							break;
						default:{
							switch(tokens[1].charAt(2)){
								case 'n':
									tokens[1] = "06";
									break;
								case 'l':
									tokens[1] = "07";
									break;
							}
						}
					}
					break;
				case 'f':
					tokens[1] = "02";
					break;
				case 'm':
					switch(tokens[1].charAt(2)){
						case 'r':
							tokens[1] = "03";
							break;
						case 'y':
							tokens[1] = "05";
							break;
					}
					break;
				case 'a':
					switch(tokens[1].charAt(1)){
						case 'p':
							tokens[1] = "04";
							break;
						case 'u':
							tokens[1] = "08";
							break;
					}
					break;
				case 's':
					tokens[1] = "09";
					break;
				case 'o':
					tokens[1] = "10";
					break;
				case 'n':
					tokens[1] = "11";
					break;
				case 'd':
					tokens[1] = "12";
					break;
			}
			StringBuilder sb=new StringBuilder();
			sb.append(tokens[2]).append("-").append(tokens[1]).append("-").append(tokens[0]).append(" ").append(tokens[3]);
			return Timestamp.valueOf(sb.toString());
		} catch (Exception e) {
			if(logger!=null) logger.warning("Error converting date: "+s+" to Timestamp.\n"+e.getMessage());
			return null;
		}
	}
}
